package com.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.meeting.dto.LoginDTO;
import com.meeting.dto.RegisterDTO;
import com.meeting.dto.UserQueryDTO;
import com.meeting.dto.UserStatusDTO;
import com.meeting.entity.Emp;
import com.meeting.vo.EmpVO;
import com.meeting.vo.PageResult;
import com.meeting.vo.Result;
import com.meeting.mapper.EmpMapper;
import com.meeting.service.EmpService;
import com.meeting.utils.JWTUtil;
import com.meeting.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Override
    public Result login(LoginDTO loginDTO) {
        Emp emp = empMapper.getByUsername(loginDTO.getUsername());
        if(emp ==null || !emp.getPassword().equals(loginDTO.getPassword())){
            return Result.error("用户名或密码错误");
        }

        if (emp.getStatus() == 0) {
            return Result.error("账户被冻结，请联系管理员");
        }

        if (emp.getStatus() == 2) {
            return Result.error("账户尚未审核通过，请联系管理员");
        }

        String token = JWTUtil.generateToken(emp.getId(),"emp");

        LoginVO vo = new LoginVO();
        vo.setName(emp.getName());
        vo.setToken(token);
        vo.setUsername(emp.getUsername());

        return Result.success(vo);
    }

    @Override
    public Result register(RegisterDTO registerDTO) {
        //验证用户名的唯一性
        LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Emp::getUsername,registerDTO.getUsername());
        Emp existingEmp = empMapper.selectOne(wrapper);
        if(existingEmp!=null){
            return Result.error("该用户名已存在");
        }
        Emp emp = new Emp();
        BeanUtils.copyProperties(registerDTO, emp);
        emp.setStatus(2);// 等待管理员审核
        empMapper.insert(emp);
        return Result.success("注册成功");
    }
    
    @Override
    public PageResult<EmpVO> listEmployees(UserQueryDTO userQueryDTO) {
        try {
            log.info("分页查询员工列表：{}", userQueryDTO);
            
            // 构建查询条件
            LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (StringUtils.hasText(userQueryDTO.getUsername())) {
                queryWrapper.like(Emp::getUsername, userQueryDTO.getUsername());
            }
            
            if (StringUtils.hasText(userQueryDTO.getName())) {
                queryWrapper.like(Emp::getName, userQueryDTO.getName());
            }
            
            if (userQueryDTO.getStatus() != null) {
                queryWrapper.eq(Emp::getStatus, userQueryDTO.getStatus());
            }
            
            // 分页查询
            PageHelper.startPage(userQueryDTO.getPage(), userQueryDTO.getPageSize());
            Page<Emp> page = (Page<Emp>) empMapper.selectList(queryWrapper);
            
            // 转换为VO
            List<EmpVO> empVOList = new ArrayList<>();
            for (Emp emp : page.getResult()) {
                EmpVO empVO = new EmpVO();
                BeanUtils.copyProperties(emp, empVO);
                
                // 设置状态文本
                switch (emp.getStatus()) {
                    case 0:
                        empVO.setStatusText("已冻结");
                        break;
                    case 1:
                        empVO.setStatusText("已启用");
                        break;
                    case 2:
                        empVO.setStatusText("待审核");
                        break;
                    default:
                        empVO.setStatusText("未知");
                }
                
                empVOList.add(empVO);
            }
            
            return new PageResult<>(page.getTotal(), empVOList);
        } catch (Exception e) {
            log.error("分页查询员工列表失败", e);
            return new PageResult<>(0L, new ArrayList<>());
        }
    }

    @Override
    public boolean updateStatus(UserStatusDTO userStatusDTO) {
        try {
            log.info("更新员工状态：{}", userStatusDTO);
            
            // 检查员工是否存在
            Emp emp = empMapper.selectById(userStatusDTO.getId());
            if (emp == null) {
                log.error("员工不存在，ID：{}", userStatusDTO.getId());
                return false;
            }
            
            // 检查状态值是否合法
            Integer status = userStatusDTO.getStatus();
            if (status != 0 && status != 1 && status != 2) {
                log.error("状态值不合法，状态：{}", status);
                return false;
            }
            
            // 更新状态
            Emp updateEmp = new Emp();
            updateEmp.setId(userStatusDTO.getId());
            updateEmp.setStatus(userStatusDTO.getStatus());
            int result = empMapper.updateById(updateEmp);
            
            return result > 0;
        } catch (Exception e) {
            log.error("更新员工状态失败", e);
            return false;
        }
    }

    @Override
    public EmpVO getEmployeeDetail(Integer id) {
        try {
            log.info("获取员工详情，ID：{}", id);
            
            Emp emp = empMapper.selectById(id);
            if (emp == null) {
                log.error("员工不存在，ID：{}", id);
                return null;
            }
            
            EmpVO empVO = new EmpVO();
            BeanUtils.copyProperties(emp, empVO);
            
            // 设置状态文本
            switch (emp.getStatus()) {
                case 0:
                    empVO.setStatusText("已冻结");
                    break;
                case 1:
                    empVO.setStatusText("已启用");
                    break;
                case 2:
                    empVO.setStatusText("待审核");
                    break;
                default:
                    empVO.setStatusText("未知");
            }
            
            return empVO;
        } catch (Exception e) {
            log.error("获取员工详情失败", e);
            return null;
        }
    }
}
